<template>
    <div style="width: 100%; margin: 0 auto">
        <el-card class="card-container">
            <div class="header">
                <h3>试卷列表</h3>
            </div>
            <el-card class="chartsGroup">
                <el-radio-group v-model="currentPaper" @change="fetchData">
                    <el-radio-button label="A">A 卷</el-radio-button>
                    <el-radio-button label="B">B 卷</el-radio-button>
                </el-radio-group>
                <div v-if="resForIfRendering" class="chartsStyle">
                    <pie :TargetScoreForProps=TargetScoreForProps v-if="!postLoading"></pie>
                    <columnChart :QuestionTypesForProps=QuestionTypesForProps v-if="!postLoading"></columnChart>
                </div>
                <div v-if="resForIfRendering" class="expand-button" @click="toggleHiddenCharts">
                    {{ showHiddenCharts ? '收起' : '查看更多图表' }}
                </div>
                <div v-if="resForIfRendering" class="hiddenCharts" :class="{ 'hidden': showHiddenCharts }">
                    <multiColumn :multi_chart_data_ForProps=multi_chart_data_ForProps v-if="!postLoading"></multiColumn>
                    <lineChart :QuestionTypes_with_score_ForProps=QuestionTypes_with_score_ForProps v-if="!postLoading">
                    </lineChart>
                </div>
            </el-card>
            <el-card>
                <div class="btgroup">
                    <el-button @click="showDialog('autoMake')" class="button">自动组卷</el-button>
                    <el-button @click="showDialog('handMake')" class="button">手动组卷</el-button>
                    <!-- <el-button @click="startExam(row)" class="button">自动组卷</el-button>
                    <el-button @click="makePaperRandomly(row)" class="button">手动组卷</el-button> -->
                </div>
            </el-card>
            <el-table :data="papers" border>
                <el-table-column align="center" width="250" prop="paperName" label="试卷名称"></el-table-column>
                <!-- <el-table-column align="center" width="120" prop="term" label="考试学期"></el-table-column> -->
                <!-- <el-table-column align="center" width="120" prop="class" label="考试班级"></el-table-column> -->
                <el-table-column align="center" width="250" prop="questionCount" label="题目数量"></el-table-column>
                <!-- <el-table-column align="center" width="100" prop="suggestTime" label="考试时间"></el-table-column> -->
                <el-table-column align="center" width="250" prop="format" label="考试形式"></el-table-column>
                <el-table-column align="center" min-width="300" label="操作">
                    <template #default="{ row }">
                        <el-button type="text" @click="edit(row)">查看/编辑</el-button>
                        <el-button type="text" @click="startExam(row)">查看题目</el-button>
                        <!-- <el-button type="text" @click="startExam(row)">组卷</el-button>
                        <el-button type="text" @click="makePaperRandomly(row)">自动组卷</el-button> -->
                        <el-button type="text" @click="remove(row)">删除</el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty></el-empty>
                </template>
            </el-table>
            <!-- <div class="footer">
                <el-button type="primary" plain @click="showDialog">添加试卷</el-button>
            </div> -->
        </el-card>
        <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :show-close="false" title="添加试卷" width="50%">
            <el-form :rules="rules" :model="form" ref="formRef" label-width="100px">
                <el-form-item label="试卷名称" prop="paperName">
                    <el-input placeholder="例:数据结构" v-model="form.paperName"></el-input>
                </el-form-item>
                <!-- <el-form-item label="考试学期" prop="term">
                    <el-input placeholder="例:第一学期" v-model="form.term"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="考试学期" prop="term">
                    <el-select v-model="form.term" placeholder="请选择考试学期">
                        <el-option label="第一学期" value="第一学期"></el-option>
                        <el-option label="第二学期" value="第二学期"></el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="考试学年" prop="academyYaer">
                    <el-input placeholder="例:2022-2023" v-model="form.academyYaer"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="考试班级" prop="class">
                    <el-input placeholder="例:2201" v-model="form.class"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="学院" prop="academy">
                    <el-input placeholder="例:计算机" v-model="form.academy"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="考试形式" prop="format">
                    <el-input placeholder="例:闭卷" v-model="form.format"></el-input>
                </el-form-item> -->
                <el-form-item label="考试形式" prop="format">
                    <el-select v-model="form.format" placeholder="请选择考试形式">
                        <el-option label="闭卷" value="闭卷"></el-option>
                        <el-option label="开卷" value="开卷"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="考试时间" prop="suggestTime">
                    <el-input placeholder="例:90" v-model="form.suggestTime"></el-input>
                </el-form-item>
                <!-- <el-form-item label="AB卷" prop="typePaper">
                    <el-input placeholder="例:A" v-model="form.typePaper"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="试卷类型" prop="typePaper">
                    <el-select v-model="form.typePaper" placeholder="请选择试卷类型">
                        <el-option label="A卷" value="A"></el-option>
                        <el-option label="B卷" value="B"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="题目数量" prop="questionCount">
                    <el-input placeholder="例:25" v-model="form.questionCount"></el-input>
                </el-form-item>
                <!-- <el-form-item label="分数" prop="score">
                    <el-input v-model="form.score"></el-input>
                </el-form-item>
                <el-form-item label="临时分数" prop="temScore">
                    <el-input v-model="form.temScore"></el-input>
                </el-form-item> -->
            </el-form>

            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ selectedPaper ? '保存' : '提交' }}</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { addPaper, GetpaperList, editPaper, delPaper, GetDetailPaper, PaperGetItemDetail, makePaperRandomly_api } from "@/api/paper";
import { getQuestionType, getTargetScore, getScoreOfSpecificPaper, getFoldableData  } from '@/api/target_item_info_input';
import { useRoute, useRouter } from 'vue-router';
import pie from '@/components/pie.vue'
import columnChart from '@/components/columnChart.vue'
import multiColumn from '@/components/multiColumn.vue'
import lineChart from '@/components/lineChart.vue'
import { useClassStore } from '@/stores/modules/class'
import { error } from "jquery";
const classStore = useClassStore()
const acs_id = classStore.classInfo.user_and_acs_id
const class_name = classStore.classInfo.class_name
const subject = classStore.classInfo.subject
const teaching_academy = classStore.classInfo.teaching_academy
const route = useRoute()
const subId = parseInt(route.params.subId)
const router = useRouter();
const formRef = ref();
const currentPaper = ref('A')

let papers = ref([
    {
        id: 1,
        paperName: "数学考试",
        subjectId: "001",
        // term: "第一学期",
        // academyYaer: "2023-2024",
        // class: "2203",
        academy: "数学学院",
        format: "闭卷",
        suggestTime: "120",
        typePaper: "A",
        questionCount: 50,
        // score: 100,
        // temScore: 0,
    },
]);
const termRegex = /^(第[一二]学期)$/;
const academyYearRegex = /^\d{4}-\d{4}$/;
const classRegex = /^\d{4}$/;
const formatRegex = /^(闭卷|开卷)$/;
const typePaperRegex = /^(A|B)$/;
const rules = ref({
    paperName: [
        { required: true, message: "请输入试卷名称", trigger: "blur" },
    ],
    // subjectId: [
    //     { required: true, message: "请输入学科", trigger: "blur" },
    // ],
    // term: [
    //     { required: true, message: "请输入考试学期", trigger: "blur" },
    //     { pattern: termRegex, message: "请输入正确格式的考试学期，例如：第一学期或第二学期", trigger: "blur" }
    // ],
    // academyYaer: [
    //     { required: true, message: "请输入考试学年", trigger: "blur" },
    //     { pattern: academyYearRegex, message: "请输入正确格式的考试学年，如：2022-2023", trigger: "blur" }
    // ],
    // class: [
    //     { required: true, message: "请输入考试班级", trigger: "blur" },
    //     { pattern: classRegex, message: "请输入正确格式的考试班级，如：2203", trigger: "blur" }
    // ],
    // academy: [
    //     { required: true, message: "请输入学院", trigger: "blur" },
    // ],
    format: [
        { required: true, message: "请输入考试形式", trigger: "blur" },
        { pattern: formatRegex, message: "请输入闭卷或开卷", trigger: "blur" }
    ],
    suggestTime: [
        { required: true, message: "请输入考试时间", trigger: "blur" },
        { type: "number", message: "考试时间必须为数字", trigger: "blur", transform: (value) => Number(value) }
    ],
    // typePaper: [
    //     { required: true, message: "请输入AB卷", trigger: "blur" },
    //     { pattern: typePaperRegex, message: "请输入A或B", trigger: "blur" }
    // ],
    questionCount: [
        { required: true, message: "请输入题目数量", trigger: "blur" },
        { type: "number", message: "题目数量必须为数字", trigger: "blur", transform: (value) => Number(value) },
    ],
    // score: [
    //     { required: true, message: "请输入分数", trigger: "blur" },
    //     { type: "number", message: "分数必须为数字", trigger: "blur" },
    // ],
    // temScore: [
    //     { required: true, message: "请输入临时分数", trigger: "blur" },
    //     { type: "number", message: "临时分数必须为数字", trigger: "blur" },
    // ],
});
const showHiddenCharts = ref(false); // 控制隐藏或显示hiddenCharts

const toggleHiddenCharts = () => {
    showHiddenCharts.value = !showHiddenCharts.value;
};
const dialogVisible = ref(false);
const form = ref({
    paperName: "",
    ACSId: acs_id,
    // term: "",
    // academyYaer: "",
    // class: "",
    academy: teaching_academy,
    format: "",
    suggestTime: "",
    typePaper: currentPaper.value,
    questionCount: "",
    // score: "",
    // temScore: "",
});
// const paperDetailItems = ref([])
// const backToList=ref(fasle)
const paperId = ref()

const makePaperRandomly = async () => {
    try {
        const res=await makePaperRandomly_api(paperId.value)
        console.log("res", res.data.mes);
        if (res.data.mes ==='未定义出题顺序'){
            ElMessage.error("未定义出题顺序")
            return
        }
        console.log("res.data.error", res.data.error.length);
        if (res.data.error && res.data.error.length !== 0) {
            const htmlString = res.data.error.map((err, index) => {
                if (index === res.data.error.length - 1) {
                    return `<div>${err}</div>`; // 最后一个错误消息不添加额外的间距
                } else {
                    return `<div style="margin-bottom: 8px;">${err}</div>`; // 其他错误消息添加间距
                }
            }).join('');
            ElMessage({
                dangerouslyUseHTMLString: true,
                message: htmlString,
                type: 'error',
                duration: 6000,
            });

            ElMessage({
                message: "已经将符合要求的题目导入试卷中",
                type: 'warning',
                duration: 6000,
                // showClose: true
            })
        }else{
            ElMessage.success("自动组卷成功")
        }


        router.push({
            name: "paperManage",
            params: {
                subId,
                paperId: paperId.value
            }
        }).then(() => {
            setTimeout(() => {
                window.scrollTo(0, 0); // 滚动到页面顶部
            }, 100); // 延迟一小段时间再执行滚动操作
        });

    } catch (error) {
        ElMessage.error("组卷失败",error)
        console.log("error", error);
    }

}
// 开始组卷后，发送试卷ID，获取试卷中的所有题目，赋值给paperDetailItems.value
const startExam = async (row) => {
    if (row.id!=undefined){
        router.push({
        name: "paperManage",
        params: {
            subId,
            paperId: row.id,
        }
        });
    }else{
        router.push({
            name: "paperManage",
            params: {
                subId,
                paperId: paperId.value
            }
        });
    }
    
}
const postLoading = ref(true)
const QuestionTypesForProps = ref([])
const TargetScoreForProps = ref([])
const QuestionTypes_with_score_ForProps = ref([]) 
const multi_chart_data_ForProps = ref([]) 
const resForIfRendering=ref(false)
// 折线图数据 QuestionTypes_with_score_ForProps
const fetchData = async ()=>{
    postLoading.value = true
    const res = await getQuestionType(acs_id, currentPaper.value)
    const res_1 = await getTargetScore(acs_id, currentPaper.value)
    const res_2 = await getScoreOfSpecificPaper(acs_id, currentPaper.value)
    const res_3 = await getFoldableData(acs_id, currentPaper.value)
    console.log("res", res.data.data);
    if (res.data.data.length===0){
        resForIfRendering.value=false
    }else{
        resForIfRendering.value = true
    }
    QuestionTypesForProps.value = res.data.data
    TargetScoreForProps.value = res_1.data.data
    QuestionTypes_with_score_ForProps.value = res_2.data.data
    multi_chart_data_ForProps.value = res_3.data.data
    postLoading.value = false
}
onMounted(() => {
    fetchData()
    refreshData()
});
const refreshData = () => {
    GetpaperList(acs_id, currentPaper.value).then((data) => {
        papers.value = data.data.data.map((paper) => {
            const {
                paper_name: paperName,
                // subject_id: subjectId,
                academy_yaer: academyYear,
                question_count: questionCount,
                ...rest
            } = paper;
            return {
                ...rest,
                paperName,
                // subjectId,
                academyYear,
                questionCount
                // index: index + 1,
            };
        });
    });
}
let selectedPaper;
const howToMakePaper=ref(null)
const showDialog = (howToMakePaper_arg) => {
    dialogVisible.value = true;
    howToMakePaper.value = howToMakePaper_arg
    form.value = {
        paperName: "",
        ACSId: acs_id,
        // term: "",
        // academyYaer: "",
        // class: "",
        academy: teaching_academy,
        format: "",
        suggestTime: "",
        typePaper: currentPaper.value,
        questionCount: "",
        // score: "",
        // temScore: "",
    };
    // if (howToMakePaper==='autoMake'){
    //     howToMakePaper.value='autoMake'
    //     makePaperRandomly()
    // } else if (howToMakePaper === 'handMake'){
    //     howToMakePaper.value='handMake'
    //     startExam()
    // }

};
let isSubmitting = false; // 添加标志变量来跟踪提交状态
const submitForm = async () => {

    if (isSubmitting) return; // 如果正在提交，则直接返回
    isSubmitting = true; // 设置提交状态为 true

try {
        await formRef.value.validate();
        papers.value = papers.value.map((paper) => {
            // console.log("paper", paper);
            // 左边的重命名变成右边的
            const {
                paperName: paper_name,
                // subjectId: subject_id,
                academyYear: academy_yaer,
                questionCount: question_count,
                ...rest
            } = paper;
            return {
                ...rest,
                paper_name,
                // subject_id,
                academy_yaer,
                question_count
                // index: index + 1,
            };
        });
    // console.log("state", selectedPaper, howToMakePaper.value);
        if (selectedPaper) {
            Object.assign(selectedPaper, form.value);
            // console.log("form.value", form.value);
            await editPaper(form.value);
            selectedPaper = null;
            ElMessage.success("试卷编辑成功");
        } else {
            // console.log("check", form.value);
            const res= await addPaper(form.value);
            // console.log("res.data", res.data);
            paperId.value=res.data.data.id
            papers.value.push({ ...form.value });
            if (howToMakePaper.value === 'autoMake') {
                makePaperRandomly()
            } else if (howToMakePaper.value === 'handMake') {
                startExam(paperId.value)
                ElMessage.success("试卷添加成功");

            }

        }
        refreshData()
        dialogVisible.value = false;
    } catch (error) {
        console.error("提交表单时出错:", error);
    } finally {
        isSubmitting = false; // 无论提交成功或失败，都将提交状态设置为 false
    }
};



const cancel = () => {
    formRef.value.resetFields();
    dialogVisible.value = false;
};

const edit = async (row) => {
    const res = await GetDetailPaper(row.id);
    const { paper_name, subject_id, suggest_time, type_paper
        , question_count, academy_yaer, ...rest } = res.data.data;
    dialogVisible.value = true;
    form.value = {
        ...rest,
        // academyYaer: academy_yaer,
        paperName: paper_name,
        subjectId: subId,
        suggestTime: suggest_time,
        typePaper: currentPaper.value,
        questionCount: question_count
    };
    selectedPaper = row;
};
const remove = (row) => {
    ElMessageBox.confirm("确定删除该试卷吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        await delPaper(row.id);
        const index = papers.value.indexOf(row);
        papers.value.splice(index, 1);
        ElMessage.success("试卷删除成功");
    });
};
</script>

<style lang="scss" scoped>
.card-container {
    margin: 20px;
    // background-color: #75c4e7;
    // width: 100%;
    .footer {
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }

    .chartsStyle {
        display: flex;
        justify-content: space-around;


    }
       .expand-button {
           text-align: center;
           cursor: pointer;
           margin: 20px;
           color: #1a89f1;
           font-weight: bold;
           border: 1px black;
           &:hover {
               text-decoration: underline;
           }
       }
    .hiddenCharts {
        display: flex;
        flex-direction: column;
        height: 0;
        overflow: hidden;
        transition: height 0.3s ease-out;

        &.hidden {
            height: auto;
        }
    }

    .btgroup {
        width: 100%;
        display: flex;

        .button {
            justify-content: center;
            padding: 15px 30px;
            background-color: #1a89f1;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            width: 100%;
            box-sizing: border-box;
        }
    }

    .header {
        h3 {
            margin-top: 2px;
            padding-bottom: 17px;
            border-bottom: 2px dotted gainsboro;
        }
    }

    .dialog-footer {
        text-align: right;
        margin-top: 20px;
    }
}
</style>
